<?php




class BuildSqlUtils {

	/**
	 * 构造insert的sql,例如:insert into user (id,username) values ('1','admin')
	 * 如果某个字段为null,insert中的value为''
	 */
	public static function buildInsertSql($tableName,$entityArray) {
		$result = "";
		if (is_array($entityArray) && !empty($entityArray)) {
			$i = 0;
			foreach ($entityArray as $key => $val) {
				$fields[$i] = $key;
				$values[$i] = $val;
				$i++;
			}
			$s_fields = "(" . implode(",", $fields) . ")";
			$s_values = "('" . implode("','", $values) . "')";
			$sql = "insert into  
                       $tableName  
                       $s_fields  
                   values  
                       $s_values";
			$result = $sql;
		} else {
			$result = false;
		}
		return $result;
	}
	
	/**
	 * 构造update的sql语句,例如:update user set id='1',username = 'admin' where id='1'
	 * 如果不想修改某个字段,将其设为null即可
	 */
	public static function bulidUpdateSql($tableName,$entityArray,$condition){
		$result = "";
		$i = 0;
		$data = '';
		if (is_array($entityArray) && !empty($tableName)) {
			foreach ($entityArray as $key => $val) {
				//val不为null
				if (isset($val)) {
					$val = $val;
					if ($i == 0 && $val !== null) {
						$data = $key . "='" . $val . "'";
					} else {
						$data .= "," . $key . " = '" . $val . "'";
					}
					$i++;
				}
			}
			if(isset($condition)){
				$sql = "update " . $tableName . " set " . $data . " where " . $condition;
			}else{
				$sql = "update " . $tableName . " set " . $data;
			}
			
			$result = $sql;
		} else {
			$result = false;
		}
		return $result;
	}

}
?>